<template>
  <div class="offline">
    <!-- 面包屑 -->
    <Headline :headline1="$t('m.AccessAdmin')+'  /  '" :headline2="$t('m.AccordingToThePeopleAuthorization')"></Headline>
    <a-card style="width: 100%">
      <div class="lass-flex">
        <a-select
          class="select-a"
          v-model="formunitdata.orgType"
          @change="handleSelectChange"
        >
          <a-select-option v-for="item in types" :value="item.code" :key="item.code"> 
            {{item.name}}</a-select-option>
      
        </a-select>
        <a-tree-select
          v-model="value"
          show-search
          style="width: 20%; height: 32px; margin-left: 15px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="Please select"
          allow-clear
          @change="checked"
          tree-default-expand-all
        >
         
          <a-tree-select-node
            v-for="item in items"
            :key="item.id"
            :cont="item"
            :value="item.custorgname"
            :title="item.custorgname"
          >
            <a-tree-select-node
              v-for="int in item.children"
              :key="int.id"
              :cont="int"
              :value="int.custorgname"
              :title="int.custorgname"
            >
              <a-tree-select-node
                v-for="ins in int.children"
                :key="ins.id"
                :cont="ins"
                :value="ins.custorgname"
                :title="ins.custorgname"
              />
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
        <a-input-search
          :placeholder="$t('m.PleaseEnterCategoryKeywords')"
          style="width: 200px; margin-left: 15px"
          size="default"
          @search="offSearch"
          v-model="fostlist.key"
        />
        <div class="chend">
          <a-checkbox :defaultChecked="fostlist.vChild" @change="lineChange">
            {{$t('m.WhetherToDisplayChildNodes')}}
          </a-checkbox>
        </div>
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="unitbtn"
            >{{$t('m.TheNewAuthorization')}}</a-button
          >
        </div>
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="downbtn"
            >{{$t('m.DeleteTheAuthorized')}}</a-button
          >
        </div>
      </div>
      <a-table
        style="margin-top: 15px; overflow-x: auto"
        :rowKey="(r, i) => r.devid"
        :columns="column"
        :data-source="datas"
        bordered
        :pagination="false"
        :row-selection="{
          onChange: perSelectChange,
          type: 'checkbox',
          selectedRowKeys: setsclete,
        }"
 
      >
        <div slot="tags" slot-scope="text, tags, i">
          <a class="flex-a" href="#" @click="unitdelete(text, tags, i)">{{$t('m.Delete')}}</a>
        </div>
      </a-table>
      <a-pagination
        class="pages"
        show-size-changer
        :default-current="1"
        :total="total"
        @change="setPages"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="setShowSizeChange"
      />
    </a-card>
    <a-modal
      :title="$t('m.SelectPersonnel')"
      width="800px"
      :visible="visibleB"
      @cancel="handleCancelB"
      :footer="null"
    >
    <a-steps :current="current">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>
    <div class="steps-content" v-if="current == 0?true:false">
      <select-tree style="margin-right: 20px" @checkData="changeTree" />
        <a-select
          style="width: 80px; margin-right: 20px"
          default-value="1"
          @change="treeChange"
        >
          <a-select-option value="1"> 职工 </a-select-option>
          <a-select-option value="2"> 学生 </a-select-option>
        </a-select>
        <a-input-search
          :placeholder="$t('m.PleaseEnterYourSearchTerms')"
          v-model="forminitialB.key"
          style="width: 200px; margin-right: 20px"
          enter-button
          @search="onSearchB"
        />
        <a-checkbox @change="onChangeA"> {{$t('m.WhetherToDisplayChildNodes')}} </a-checkbox>

        <a-transfer
          style="margin-top: 20px"
          :locale="{ itemUnit: '项', itemsUnit: '项' }"
          :data-source="mockData"
          :target-keys="targetKeys"
          :show-search="showSearch"
          :filter-option="
            (inputValue, item) => item.title.indexOf(inputValue) !== -1
          "
          :show-select-all="false"
          @change="onChange"
        >
          <template
            slot="children"
            slot-scope="{
              props: { direction, filteredItems, selectedKeys },
              on: { itemSelectAll, itemSelect },
            }"
          >
            <a-table
              :row-selection="
                getRowSelection({
                  selectedKeys,
                  itemSelectAll,
                  itemSelect,
                })
              "
              :columns="direction === 'left' ? leftColumns : rightColumns"
              :data-source="filteredItems"
            />
          </template>
        </a-transfer>
    </div>
     <div class="steps-content" v-if="current == 1?true:false">
      <select-tree-area @checkData="areaSelect" style="margin-right:10px" />
      <a-input-search
      style="width:200px;margin-right:10px"
          class="input-a"
          placeholder="请输入权限组关键词"
          v-model="timelist.key"
          @search="lostSearch"
        />
        <a-checkbox :defaultChecked="timelist.vChild" @change="contChange">
            {{$t('m.WhetherToDisplayChildNodes')}}
          </a-checkbox>
      <vxe-table
style="margin-top:20px"
          resizable
          :tree-config="{transform: true, rowField: 'id', parentField: 'parentId'}"
          :data="dataroles"
          :checkbox-config="{labelField: 'name', highlight: true}"
          @checkbox-change="selectChangeEvent">
          <vxe-column type="checkbox" title="门" width="280" tree-node></vxe-column>
          <vxe-column field="timeInterval" :title="$t('m.Period')"></vxe-column>
          <vxe-column field="weekvalue" :title="$t('m.openDay')"></vxe-column>
          <vxe-column field="machineid" :title="$t('m.deviceNumber')"></vxe-column>
        </vxe-table>
    </div>
     <div class="steps-content" v-if="current == 2?true:false">
       <h3>{{$t('m.periodofvalidity')}}</h3>
      <a-date-picker show-time placeholder="Select Time"
      v-model="a"
       @change="dataChange" />
    </div>
    <div class="steps-action">
      <a-button v-if="current < steps.length - 1" type="primary" @click="next">
        Next
      </a-button>
      <a-button
        v-if="current == steps.length - 1"
        type="primary"
        @click="setOk"
      >
        Done
      </a-button>
      <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
        Previous
      </a-button>
    </div>
    </a-modal>
    <Delete ref="delete" :dalete="dalete" @confirm="ondelete"></Delete>
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Modal from "@/components/common/Modal";
import SelectTree from "@/components/common/SelectTree";
import SelectTreeArea from "@/components/common/SelectTreeArea";
import Delete from "@/components/Delete";
import { getPerages } from "@/api/perAges";
import { getdiction } from "@/api/dictionaries";
import { getStaffOrStudInfoList, } from "@/api/faceRecognition";
import {getDeviceTimeLists,saveAuthorize} from "@/api/entrance/entranceguard"
import difference from "lodash/difference";
import {
  AuthorizeList,
  getdelAuthorize
} from "@/api/entrance/entranceguard";

export default {
  name: "PerCapita",
  components: {
    Headline,
    Modal,
    Delete,
    SelectTree,
    SelectTreeArea
  },
  data() {
    return {
      a:'',
      dataroles: [],
      timelist: {
        key: "",
        areaCode: "",
        vChild: true,
      },
      visibleB:false,
      value: "",
      items: [],
      formunitdata: {
        orgType: "1",
        key: "",
      },
      fostlist: {
        orgCode: "",
        key: "",
        vChild: true,
        start: 0,
        limit: 10,
        page: 1,
      },
      fromdic: {
        groupcode: "SYS0000025",
        insertall: "-1|全部",
        where: "code<> -1 and code <> -100",
      },
      diction: [],
      setsclete: [],
      // 配置数据
      column: [
        {
          title: this.$t('m.mergingphase'),
          dataIndex: "mergestatus",
            customRender: function (text, record, index) {
             if(text==0){
                 return "待合并"
             }else if(text==1){
                 return "已合并"
             }else if(text==2){
                 return "待删除"
             }
          },
        },
        {
          title: this.$t('m.jobnumber'),
          dataIndex: "stafforstucode",
        },
        {
          title: this.$t('m.Name'),
          dataIndex: "stafforstuname",
        },
        {
          title: this.$t('m.CardNumber'),
          dataIndex: "cardno",
        },
        {
          title: this.$t('m.deviceNumber'),
          dataIndex: "machineid",
        },
        {
          title: this.$t('m.EquipmentName'),
          dataIndex: "devname",
        },
        {
          title: this.$t('m.NumberOfGate1Period'),
          dataIndex: "door1",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.NumberOfGate2Period'),
          dataIndex: "door2",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.NumberOfGate3Period'),
          dataIndex: "door3",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.NumberOfGate4Period'),
          dataIndex: "door4",
          customRender: function (text, record, index) {
            let subid = text.split(",");
            let arr = [];
            subid.map((item, index) => {
              if (item == 1) {
                arr.push(index + 1);
              }
            });
            return arr.join(",");
          },
        },
        {
          title: this.$t('m.AuthorizationType'),
          dataIndex: "authwayname",
        },
        {
          title: this.$t('m.periodofvalidity'),
          dataIndex: "createdate",
        },
      ],
      datas: [],
      total: 0,
      dalete: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToDeleteThisData'),
      },
      ids: "",
      dictionfrom: {
        groupcode: "SYS0000019",
        insertall: "",
        where: "",
        page: 1,
        start: 0,
        limit: 25,
      },
      types:[],
      current: 0,
      steps: [
        {
          title: 'First',
          content: 'First-content',
        },
        {
          title: 'Second',
          content: 'Second-content',
        },
        {
          title: 'Last',
          content: 'Last-content',
        },
      ],
      forminitialB: {
        start: 0,
        limit: 10,
        page: 1,
        key: "",
        infoType: 1,
        status: 1,
        vChild: false,
        ymOrgTreeCode: "",
      },
      mockData: [],
      targetKeys: [],
      selectedKeys: [],
      showSearch: false,
      disabled: false,
      leftColumns: [
        {
          title: this.$t('m.jobnumber'),
          dataIndex: "stafforstucode",
        },
        {
          title: this.$t('m.Name'),
          dataIndex: "stafforstuname",
        },
        {
          title: this.$t('m.Sex'),
          dataIndex: "sex",
          customRender: function (text) {
            if (text == "1") {
              return "男";
            } else {
              return "女";
            }
          },
        },
        {
          title: this.$t('m.CardNumber'),
          dataIndex: "cardno",
        },
        {
          title: this.$t('m.AffiliatedUnit'),
          dataIndex: "orgname",
        },
      ],
      rightColumns: [
        {
          dataIndex: "stafforstuname",
          title: this.$t('m.Name'),
        },
      ],
      saveForminitial:{
        infoId:'',
        devData:[],
        endDate:''
      }
    };
  },
  created() {
    // 请求数据
    this._getPerages();
    this._getdiction();
  },
  methods: {
    dataChange(e){
      console.log(e)
    },
    selectChangeEvent ({ records }) {
      let devList = []
      let dataList = []
      records.forEach(item => {
        if(item.children.length !== 0) {
        devList.push(item)
        }
      })
      devList.forEach(citem => {
        let num = []
        for (let index = 0; index < 16; index++) {
          if(index > citem.children.length-1) {
            num.push(0)
          } else {
            num.push(1)
          }
        }
        // devInfo.devId = citem.id
        let doorDemo = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        dataList.push({devId:citem.id,machineId:citem.machineid,
        devSn:citem.devsn,door1:num.join(','),door2:doorDemo,door3:doorDemo,door4:doorDemo})
      })
      this.saveForminitial.devData = JSON.stringify(dataList)
      console.log(dataList)
    },
    lostSearch() {
      this._getDeviceTimeLists();
    },
    contChange() {
      this.timelist.vChild = !this.timelist.vChild;
      this._getDeviceTimeLists();
    },
    _getDeviceTimeLists() {
      getDeviceTimeLists({ params: this.timelist }).then((res) => {

        res.data.forEach(item => {
          item.parentId = null
          for (let index = 0; index < item.children.length; index++) {
            item.children[index]['name'] = '时段方案' + (index+1)
            
          }
        })

        // res.data.forEach(item => {
        //   for (let index = 0; index < item.children.length; index++) {
        //     item.children[index]['parentId'] = item.id
        //     res.data.push(item.children[index])
        //   }
        // })
        res.data.forEach(item => {
             for (let index = 0; index < item.children.length; index++) {
            item.children[index]['parentId'] = item.id
            res.data.push(item.children[index])
          }
            if(item.starttime) {
            item['timeInterval'] = item.starttime + '-' + item.endtime
          }
        })
        res.data.forEach(item => {
            if(item.starttime) {
            item['timeInterval'] = item.starttime + '-' + item.endtime
          }
        })
        res.data.forEach(item => {
          if(item.weekvalue) {
            let demo = item.weekvalue.split(',')
            let day = []
            for (let index = 0; index < demo.length; index++) {
              if(demo[0] == 1) {
                day.push('周日')
                
              }
              if(demo[1] == 1) {
                day.push('周一')
              }
              if(demo[2] == 1) {
                day.push('周二')
              }
              if(demo[3] == 1) {
                day.push('周三')
              }
              if(demo[4] == 1) {
                day.push('周四')
              }
              if(demo[5] == 1) {
                day.push('周五')
              }
              if(demo[6] == 1) {
                day.push('周六')
              }
              if(demo[7] == 1) {
                day.push('假日')
              }
              break
              
            }
            item.weekvalue = day
          }
        })
        console.log(res.data);
        this.dataroles = res.data;
      });
    },
    areaSelect(e) {
      console.log(e);
    },
    onChange(targetKeys, direction, moveKeys) {
      console.log(targetKeys);
      this.saveForminitial.infoId = targetKeys.join(',')
      console.log(this.saveForminitial.infoId)
      this.targetKeys = targetKeys;
    },
     onChangeA(e) {
      console.log(e.target.checked);
      this.forminitialB.vChild = e.target.checked;
      this.getStaffOrStudInfoData();
    },
    onSearchB() {
      this.getStaffOrStudInfoData();
    },
    getStaffOrStudInfoData() {
      getStaffOrStudInfoList({ params: this.forminitialB })
        .then((res) => {
          this.mockData = res.data.data.map((item) => {
            return {
              key: item.id + "",
              infotype: item.infotype,
              orgname: item.orgname,
              property: item.property,
              sex: item.sex,
              stafforstucode: item.stafforstucode,
              stafforstuname: item.stafforstuname,
              ymorgid: item.ymorgid,
              status: item.status,
              ymorgtreecode: item.ymorgtreecode,
            };
          });
          this.dataC = res.data.data;
          // this.totalC = res.data.total
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    treeChange(e) {
      this.forminitialB.infoType = e;
      this.getStaffOrStudInfoData();
      console.log(e);
    },
    changeTree(e) {
      this.forminitialB.ymOrgTreeCode = e.ymorgtreecode;
      this.getStaffOrStudInfoData();
      console.log(e);
    },
    setOk(){
      console.log(this.a)
      this.saveForminitial.endDate = this.$moment(this.a._d).format("YYYY-MM-DD HH:mm:ss")
      console.log(this.saveForminitial)
      saveAuthorize(this.saveForminitial)
      .then(res => {
        if (res.data.success == true) {
              this.$message.success(res.data.msg);
              this.chend()
            } else {
              this.$message.warning(res.data.msg);
            }
      })
      .catch(err => {
        this.$message.error("操作失败");
      })
      this.a = ''
      this.visibleB = false
      this.targetKeys = [],
      this.current = 0
    },
    next() {
      this._getDeviceTimeLists()
      if (this.targetKeys.length <= 0)
        return this.$message.warning("请选择人员信息");
      this.current++;
    },
    prev() {
      this.current--;
    },
    getRowSelection({ selectedKeys, itemSelectAll, itemSelect }) {
      return {
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          // console.log(key)
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    },
    handleCancelB(){
      this.visibleB = false
    },
    //获取字典
    _getdiction() {
      getdiction({ params: this.dictionfrom }).then((res) => {
        console.log(res);
        this.types = res.data.data;
      });
    },
    _getPerages() {
      getPerages({ params: this.formunitdata })
        .then((res) => {
          console.log(res);
          if (res.data) {
            this.items = res.data;
            this.$message.success("获取数据成功");
          }
        })
        .catch((err) => {
          this.$message.error("获取数据失败");
        });
    },
    chend() {
      AuthorizeList({ params: this.fostlist }).then((res) => {
        console.log(res);
        this.total = res.data.total;
        this.datas = res.data.data;
      });
    },
    //tree选中
    checked(value, label, extra) {
      console.log(extra.triggerNode.$attrs.cont);
      //判断是否选中值了
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        this.fostlist.orgCode = cont.ymorgtreecode;
        this.chend();
      }
    },
    //下拉选中执行
    handleSelectChange() {
      this._getPerages();
    },
    //搜索
    offSearch() {
      this.chend();

    },
   
    //合并授权
    unitbtn() {
      this.visibleB = true
      this.getStaffOrStudInfoData()
    },
    //删除授权
    downbtn() {
    if(this.setsclete.length==0) return this.$message.error("请选择要删除授权的数据")
      this.$refs.delete.visible = true;
    },
    //确定
    ondelete() {
      getdelAuthorize({ ids: this.ids })
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
             this.chend();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.delete.visible = false;
    },
    //表单选中
    perSelectChange(select, text) {
      console.log(select, text);
      this.setsclete = select;
      let str = select.join(",");
      this.ids = str;
    },
    //子节点
    lineChange() {
      this.fostlist.vChild = !this.fostlist.vChild;
      this.chend();
    },

    // 分页操作功能
    setShowSizeChange(page, limit) {
      this.fostlist.page = page;
      this.fostlist.limit = limit;
      this.fostlist.start = (page - 1) * limit;
       this.chend();
    },
    setPages(page, pageSize) {
      this.fostlist.page = page;
      this.fostlist.limit = pageSize;
      this.fostlist.start = (page - 1) * pageSize;
      this.chend();
    },
  },
};
</script>

<style scoped lang="scss">
// .lass-flex {
//   display: flex;
//   align-items: center;
// }
// .select-a {
//   width: 100px;
// }
// .chend {
//   margin-left: 15px;
// }
// .btn-dispos {
//   margin-left: 15px;
// }
// /deep/ .ant-spin-nested-loading{
//     width: 2000px;
// }
// /deep/ .ant-table-wrapper{
//     width: 100%;
//     overflow-x: auto;
// }
//   ::-webkit-scrollbar{
//     width: 15px;
//     height: 15px;
//     background-color: #F5F5F5;
//   }

//   /*定义滚动条轨道 内阴影+圆角*/
//   ::-webkit-scrollbar-track {
//     box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
//     -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
//     border-radius: 10px;
//     background-color: #F5F5F5;
//   }

//   /*定义滑块 内阴影+圆角*/
//   ::-webkit-scrollbar-thumb{
//     border-radius: 10px;
//     box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
//     -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
//     background-color: #c8c8c8;
//   }
</style>